import React, { ReactNode } from "react";
import { Product } from "../interface";
import ProductCategoryRow from "./ProductCategoryRow";
import ProductRow from "./ProductRow";

interface ProductTableProps {
  products: Product[];
  filterText: string;
  inStockOnly: boolean;
}
/**
 * (淡紫色)根据用户输入，展示盒过滤清单
 * @props ProductTableProps
 * @returns 函数组件
 */
const ProductTable: React.FC<ProductTableProps> = ({ products, filterText, inStockOnly }) => {
  const rows: ReactNode[] = [];
  let lastCategory: unknown = null;

  products.forEach(product => {
    if (
      filterText !== undefined &&
      filterText.trim() !== "" &&
      product.name.toLowerCase().indexOf(filterText.trim().toLowerCase()) === -1
    ) {
      return;
    }
    if (inStockOnly && !product.stocked) {
      return;
    }
    if (product.category !== lastCategory) {
      rows.push(<ProductCategoryRow category={product.category} key={product.category} />);
    }

    rows.push(<ProductRow product={product} key={product.name} />);

    lastCategory = product.category;
  });

  return (
    <section>
      <table>
        <thead>
          <tr>
            <th>Name</th>
            <th>Price</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    </section>
  );
};
export default ProductTable;
